package com.ceshi.controller;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.ceshi.meta.User;
import com.ceshi.service.UserService;

@Controller
public class LoginAction {
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(ModelMap map) {
		// map.addAttribute("user");
		return "login";
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public void logout(HttpServletRequest req, HttpServletResponse resp, ModelMap map) {
		HttpSession session = req.getSession();
		session.invalidate();
		try {
			resp.sendRedirect("/");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/api/login", method = RequestMethod.POST)
	public String login(@RequestParam String userName, @RequestParam String password, HttpServletRequest req,
			ModelMap map) {

		ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
		UserService login = context.getBean(UserService.class);

		System.out.println("login:" + userName + "|" + password);
		// start session
		HttpSession session = req.getSession();

		int iret = login.loginvalid(userName, password);

		if (iret == -1) {

			session.invalidate();
			System.out.println("登录失败，用户不存在");

			map.addAttribute("code", "400");
			map.addAttribute("message", "用户不存在");
			map.addAttribute("result", false);

		} else if (iret == 0) {

			User user = login.getUser();
			session.setAttribute("userid", user.getUserId());
			session.setAttribute("username", user.getUserName());
			session.setAttribute("nickname", user.getNickName());
			session.setAttribute("usertype", user.getUserType());
			System.out.println("登录成功:" + userName);

			map.addAttribute("code", "200");
			map.addAttribute("message", "登录成功");
			map.addAttribute("result", true);

		} else {

			session.invalidate();
			System.out.println("登录失败，密码错误");

			map.addAttribute("code", "400");
			map.addAttribute("message", "密码错误");
			map.addAttribute("result", false);

		}

		return "defaultViews";
	}

}